package org.redrock.test.interceptor.impl;

import com.google.gson.Gson;
import org.redrock.test.bean.RequestInfo;
import org.redrock.test.config.WeixinConfig;
import org.redrock.test.interceptor.BaseInterceptor;
import org.redrock.test.interceptor.bean.SnsapiBase;
import org.redrock.test.repository.NetworkRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

//public class SnsapiBaseAuth implements BaseInterceptor {
//
//    private NetworkRepository networkRepository = new NetworkRepository();
//
//    private String key = SnsapiBase.class.toString();
//    private String getCodeApiFormat = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//    private String getOpenidApiFormat = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
//
//    @Override
//    public boolean interceptor(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, WeixinConfi) throws Exception {
//        if (httpServletRequest.getSession().getAttribute(key) != null) {
//            return true;
//        }
//        String code = httpServletRequest.getParameter("code");
//        if (!StringUtils.isEmpty(code)) {
//            String getOpenidUrl = String.format(getOpenidApiFormat, weixinConfig.getAppId(), weixinConfig.getSecret(), code);
//            RequestInfo requestInfo = new RequestInfo(
//                    "get",
//                    getOpenidUrl
//            );
//            String data = networkRepository.curl(requestInfo);
//            Gson gson = new Gson();
//            SnsapiBase snsapiBase = gson.fromJson(data, SnsapiBase.class);
//            if (ObjectUtils.isEmpty(snsapiBase)) {
//                //...
//                return false;
//            }
//            httpServletRequest.getSession().setAttribute(key, snsapiBase);
//            httpServletRequest.setAttribute(key, snsapiBase);
//            return true;
//        }
//        String redirectUrl = URLEncoder.encode(weixinConfig.getRedirect() + httpServletRequest.getRequestURI(), "UTF-8");
//        String getCodeUrl = String.format(getCodeApiFormat, weixinConfig.getAppId(), redirectUrl);
//        httpServletResponse.sendRedirect(getCodeUrl);
//        return false;
//    }
//}